import { userStore } from '@/store/modules/user'

/**
 *uniapp跳转的简单封装,暂不考虑系统其他跳转类型
 * @param url  跳转的路径
 * @param redirectTo  是否关闭当前页面跳转下一个页面
 * @param config 跳转的设置
 */
const goTo = (url: string, redirectTo: boolean = false, config?: object) => {
    if (redirectTo) {
        // redirectTo
        uni.redirectTo({
            url,
            ...config,
        })
    } else {
        // 普通跳转
        uni.navigateTo({
            url,
            ...config,
        })
    }
}

/**
 *uniap返回前面若干页(默认为1)的简单封装
 * @param delta  返回的页数
 * @param config 返回的设置
 */
const goBack = (delta: number = 1, config?: object) => {
    uni.navigateBack({
        delta,
        ...config,
    })
}

/**
 *格式化扫码内容
 */

const formatScan = (code: string) => {
    if (code.length < 30) return code
    const handleStr = (start: number, end: number) => code.substring(start, end)
    const newCode = [handleStr(0, 11), handleStr(11, 14), handleStr(14, 16), handleStr(16, 30)].join('-')
    return newCode
}

/**
 * 按钮即菜单的鉴权函数,因为app端无法利用自定义指令的el来控制样式,可利用本函数搭配v-show实现鉴权目的
 */

const hasRight = (right?: string[]) => {
    const { rightList } = userStore()

    // 如果没有传递鉴权数组默认显示
    if (!right) return true
    // 如果没有后端的权限数组,全部隐藏
    if (!rightList || !rightList.length) return false

    // 其余情况正常判断,只要传入的权限中有一个满足即展示
    let flag = false
    for (const item of right) {
        if (rightList.includes(item)) flag = true
    }
    return flag
}

/**获取扫码轮胎数 */
const getTiresNum = (list: any) =>
    computed(() => {
        // 没有数据时返回0
        if (!list || !list.length) return 0
        let count = 0
        list.forEach((scan: { code: string; type: 'success' | 'error' }) => {
            const { code, type } = scan
            if (type === 'error') return
            const tiresNum = (code.substring(14, 16) as unknown as number) - 0
            count += tiresNum
        })

        return count
    })

export { goTo, goBack, formatScan, hasRight, getTiresNum }
